package com.we823.cms.repository.service.sys;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.we823.cms.common.utils.StringUtil;
import com.we823.cms.model.sys.User;
import com.we823.cms.repository.dao.sys.UserMapper;
import com.we823.cms.repository.service.AbstractBaseService;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;

@Service("userService")
@Scope("prototype")
public class UserService extends AbstractBaseService<User, Integer> {

	private Logger logger = LoggerFactory.getLogger(UserService.class);
	
	private UserMapper userMapper;

	private @Resource RoleService roleService;
	private @Resource RoleResourcePermissionService roleResourcePermissionService;
	
	@Autowired
	public UserService(UserMapper userMapper) {
		super(userMapper);
		this.userMapper = userMapper;
	}

	public User findByUsername(String username) {
		logger.debug("findByUsername...");
		User user = new User();
		user.setUsername(username);
		List<User> userModels = userMapper.select(user);
		if(userModels!=null && userModels.size()>0){
			return userModels.get(0);
		}
		return null;
	}

	public Set<String> findStringRole(User userModel) {
		Set<String> result = Sets.newHashSet();
		if(userModel!=null) {
			List<Integer> roleidList = StringUtil.stringToIntList(userModel.getRoleIds());
			result = roleService.findByRoleIdIn(roleidList);
		}
		return result;
	}

	public Set<String> findStringPermission(User userModel) {
		Set<String> permissionSet = new HashSet<>();
		if(userModel!=null) {
			String roleids = userModel.getRoleIds();
			if(!StringUtils.isBlank(roleids)) {
				List<Integer> roleidList = StringUtil.stringToIntList(roleids);
				if(roleidList!=null && roleidList.size()>0) {
					permissionSet = roleResourcePermissionService.findStringPermissionByRoleIdIn(roleidList);
				}
			}
		}
		
		return permissionSet;
	}
}
